import 'package:flutter/material.dart';
import 'package:hello_flutter/base/index.dart';

import '../widgets/keep_alive_wrapper.dart';

class PageViewAndCacheWidget extends BasePage {
  const PageViewAndCacheWidget({super.key, this.title = 'PageViewAndCache'});

  final String title;

  @override
  String getPageTitle() => title;

  @override
  Widget buildBody(BuildContext context) {
    var children = <Widget>[];

    for (int i = 0; i < 6; i++) {
      children.add(KeepAliveWrapper(
        keepAlive: false,
        child: _Page(
          keepAlive: true,
          text: i,
        ),
      ));
    }

    return PageView(
      scrollDirection: Axis.vertical,
      pageSnapping: true,

      /// 可缓存当前页面前后各一页, 但这不是最优的解决方案
      allowImplicitScrolling: true,
      children: children,
    );
  }
}

class _Page extends StatefulWidget {
  const _Page({super.key, this.keepAlive = true, required this.text});

  final bool keepAlive;
  final int text;

  @override
  State<_Page> createState() => _PageState();
}

/// 混入 AutomaticKeepAliveClientMixin 实现缓存
class _PageState extends State<_Page> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    print('Page build ${widget.text}');
    return Container(
      color: widget.text % 2 == 0 ? Colors.purple : null,
      child: Center(
        child: Text(
          widget.text.toString(),
          textScaler: const TextScaler.linear(5),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => widget.keepAlive;
}
